<template>
  <div class="my-address">
    <van-radio-group v-model="radio">
      <div class="address_list" v-for="(item,index) in list" :key="index" @click="changeDefailt(index)">
        <van-cell-group inset :border="false" class="address-item">
          <van-cell :title="item.name+'  '+item.phone" :label="item.address+'  '+item.street_name" class="address-info" />
          <van-cell class="address-option">
            <template #title>
              <van-radio ref="isDefault" :name="item.address_id"><span :class="radio==item.address_id?'radio-checked':''">默认地址</span></van-radio>
            </template>
            <template #right-icon>
              <van-button class="options" type="default" size="mini" :icon="require('@/assets/img/my/edit.png')" @click.stop="handleEdit(item)"></van-button>
              <van-button class="options" type="default" size="mini" :icon="require('@/assets/img/my/delete.png')" @click.stop="handleDelete(item)"></van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </van-radio-group>
    <van-empty description="暂无地址" v-if="list.length == 0" />

    <div class="newly-added">
      <van-button type="primary" class="button" block native-type="submit" round @click="handleNewsAddress">添加新地址</van-button>
    </div>

    <van-popup v-model="showAddressInfo" position="bottom" closeable round class="popup-input" @close="clear">
      <!-- 
      <van-address-edit :address-info="addressInfo" :area-list="areaList" :show-delete="buttonShow" show-set-default @save="handleSave" @delete="handleDelete" @change-area="changeArea" /> -->
      <van-form @submit="handleSave" class="form">
        <van-field v-model="form.name" label="姓名" placeholder="请输入姓名" :rules="[{ required: true, message: '请输入正确姓名' }]" />
        <van-field v-model="form.phone" label="电话" placeholder="请输入电话" :rules="[{ validator: asyncValidator, message: '请输入正确电话' }]" />
        <van-cell title="选择省市区" is-link @click="(showCity=true)" v-model="city" :rules="[{ required: true, message: '请输入选择省市区' }]" />
        <van-cell title="选择街道" is-link @click="(showStreet=true)" v-model="street" :rules="[{ required: true, message: '请输入选择街道' }]" />
        <van-field v-model="form.detail" label="详细地址" placeholder="请输入详细地址" :rules="[{ required: true, message: '请输入详细地址' }]" />
        <van-cell title="是否为默认地址">
          <van-switch v-model="is_default" active-color="#ee0a24" inactive-color="#dcdee0" />
        </van-cell>
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" class="confirmBtn">提交</van-button>
        </div>
      </van-form>
      <!-- <van-cell>
        <van-button type="primary" round class="confirmBtn">确认</van-button>
      </van-cell> -->
    </van-popup>
    <van-popup v-model="showCity" position="bottom">
      <van-area title="选择地址" :area-list="areaList" @confirm="changeArea" @cancel="showCity=false" :value="cityCode" />
    </van-popup>
    <van-popup v-model="showStreet" position="bottom">
      <van-picker title="选择街道" show-toolbar :columns="streetlist" @confirm="onConfirm" @cancel="showStreet=false" value-key="name" :default-index="defaultIndex" />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import { Toast, Dialog } from 'vant';
export default {
  data () {
    return {
      radio: null,
      list: [],
      areaList,
      nowareaList: [],
      showAddressInfo: false,
      showCity: false,
      showStreet: false,
      chosenAddressId: "1",
      addressInfo: {}, //新建地址
      buttonShow: "",
      edit_id: "",
      streetlist: [],
      street: "",
      city: "",
      cityCode: "",
      streetCode: '',
      defaultIndex: 0,
      form: {
        name: "",
        phone: '',
        detail: '',
        street_id: '',
      },
      is_default: false,
    }
  },
  created () {
    this.getMyAddress()
  },
  methods: {
    //清除地址数据
    clear () {
      this.form = {
        name: "",
        phone: '',
        detail: '',
        street_id: '',
      }
      this.street = ""
      this.city = ""
      this.is_default = false
      this.defaultIndex = 0
    },
    // 获取地址列表
    getMyAddress () {
      this.$axios.get(this.$api.getaddresslist).then((res) => {
        this.list = res.data.data.map((item) => {
          return {
            ...item,
            name: item.name,
            tel: item.phone,
            address: item.province_name + item.city_name + item.area_name + item.detail,
            addressDetail: item.detail,
            county: item.district,
            isDefault: item.is_default == 1 ? true : false,
            areaCode: JSON.stringify(item.area_id),
          };
        });
        for (let index = 0; index < this.list.length; index++) {
          const element = this.list[index]
          if (element.is_default == 1) this.radio = element.address_id
        }
      });
    },
    // 获取地址列表
    getMyStreet (code) {
      this.$axios.get(this.$api.streetlist, {
        params: {
          area_id: code
        }
      }).then((res) => {

        this.streetlist = res.data.data
        if (this.buttonShow) {
          this.streetlist.forEach((ele, index) => {
            if (ele.name == this.street) {
              this.defaultIndex = index
            }
          })
        }
      })
    },
    // 切换默认地址
    changeDefailt (index) {
      this.$nextTick(function () {
        // 运用refs防止van-radio-group切换选项时出现相同id重复的问题
        this.$refs.isDefault[index].toggle()
      });
      this.$axios.post(this.$api.setdefaultaddress, {
        address_id: this.$refs.isDefault[index].name
      }).then(() => {
        Toast.success('设置成功')
      });
    },
    handleSave () {


      if (this.buttonShow == false) {
        this.$axios.post(this.$api.addaddress, {
          ...this.form,
          province_id: this.nowareaList[0].code, //省id
          province_name: this.nowareaList[0].name, //省
          city_id: this.nowareaList[1].code, //市id
          city_name: this.nowareaList[1].name, //市
          area_id: this.nowareaList[2].code, //区id
          area_name: this.nowareaList[2].name, //区

          is_default: this.is_default ? 1 : 0, //是否默认 1-默认，0-非默认,
        }).then((res) => {

          if (res.data.code == 1) {
            Toast.success("添加成功");
            this.nowareaList = []
            this.showAddressInfo = false;
            this.getMyAddress();
          } else {

            Toast.fail(res.data.msg)
          }
        });
      } else {
        //编辑地址
        this.$axios.post(this.$api.oneaddress, {
          handle: "ajax", //传ajax表示编辑
          ...this.form,
          province_id: this.nowareaList[0].code, //省id
          province_name: this.nowareaList[0].name, //省
          city_id: this.nowareaList[1].code, //市id
          city_name: this.nowareaList[1].name, //市
          area_id: this.nowareaList[2].code, //区id
          area_name: this.nowareaList[2].name, //区

          is_default: this.is_default == true ? 1 : 0, //是否默认 1-默认，0-非默认,
        }).then((res) => {
          if (res.data.code == 1) {
            Toast.success("修改成功")
            this.nowareaList = []
            this.showAddressInfo = false
            this.getMyAddress()
          } else {

            Toast.fail(res.data.msg)
          }

        })
      }
    },
    // 添加新地址
    handleNewsAddress () {
      this.showAddressInfo = true
      this.buttonShow = false
      this.addressInfo = {}
    },
    // 切换省市区
    changeArea (val) {

      this.city = val[0].name + ' ' + val[1].name + ' ' + val[2].name
      this.nowareaList = val
      this.showCity = false
      this.getMyStreet(this.nowareaList[2].code)
    },
    onConfirm (value) {
      this.street = value.name

      this.showStreet = false
      this.form.street_id = value.id


    },
    // 编辑地址
    handleEdit (item) {
      // this.nowareaList = []
      // this.edit_id = item.address_id
      this.nowareaList = [
        { code: item.province_id, name: item.province_name },
        { code: item.city_id, name: item.city_name },
        { code: item.area_id, name: item.area_name },
      ]

      this.cityCode = String(item.area_id)
      this.city = item.province_name + ' ' + item.city_name + ' ' + item.area_name
      this.street = item.street_name
      this.form.street_id = item.street_id
      this.getMyStreet(item.area_id)
      // this.addressInfo = this.list.filter((e) => {
      //   return item.address_id == e.address_id
      // })[0]
      //buttonShow： true是编辑，false是新建
      this.form.name = item.name
      this.form.address_id = item.address_id
      this.form.phone = item.phone
      this.form.detail = item.detail
      this.is_default = item.is_default == 1 ? true : false

      this.showAddressInfo = true
      this.buttonShow = true
    },
    // 删除地址
    handleDelete (item) {
      Dialog.confirm({
        title: '提示',
        message: '确认删除该地址吗？',
      }).then(() => {
        this.$axios.post(this.$api.deladdress, {
          address_id: item.address_id
        }).then(() => {
          Toast.success('删除成功')
          this.getMyAddress()
        });
      }).catch(() => {
        // on cancel
      });
    },
    // 异步校验电话返回 Promise
    asyncValidator (val) {

      let test1 = /^1[3456789]\d{9}$/
      return test1.test(val);
    },
  },
}
</script> 

<style lang="less" scoped>
.my-address {
  position: relative;
  height: 100%;
  padding: 16px 0 70px;
  .address_list {
    margin-bottom: 16px;
  }
  .address-info {
    padding-top: 18px;
    padding-bottom: 18px;
  }
  .address-item {
    /deep/.van-cell__title,
    /deep/ .van-cell__label {
      color: #201d1d;
      font-size: 13px;
    }
    .address-option {
      align-items: center;
      .radio-checked {
        color: @green;
      }
      .van-cell__title,
      .van-button--default {
        border: 0;
        font-size: 14px;
        color: #797777;
      }
      .options {
        margin-left: 12px;
      }
    }
  }
  .newly-added {
    position: fixed;
    width: 90%;
    left: 50%;
    bottom: 18px;
    transform: translateX(-50%);
    /deep/.van-button__text {
      font-size: 16px;
    }
  }
  .popup-input {
    /deep/.van-switch--on {
      background-color: @green;
    }
    /deep/ .van-address-edit__buttons {
      .van-button--round {
        border-radius: 50px;
      }
      .van-button--danger {
        border: 0;
        background-color: @green;
      }
    }
  }
}
.button {
  background: #ff7733 !important;
  border: 1px solid #ff7733;
}
.form {
  margin-top: 37.5px;
  .confirmBtn {
    width: 343px;
    height: 43px;
    background: #ff7733;
    border: 1px solid #ff7733;
  }
}
</style>